<template>
  <div>
    <el-upload
      list-type="picture-card"
      action=""
      :http-request="upload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :file-list="fileList"
      :limit="limit"
      :class="{hidden: fileList.length >= limit}"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="showDialog" title="图片预览" @close="closeFn">
      <img width="100%" :src="dialogImageUrl" alt="" style="width: 100%; height: 500px;object-fit: cover">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      showDialog: false,
      dialogImageUrl: '',
      fileList: []
    }
  },
  created() {
    this.cos = new COS({
      SecretId: 'AKIDAD3e082kV6Zv76qLfnlhV7VfbMuELFyU',
      SecretKey: 'LTN6bswmQs8DC1d3GEzbzBAxXv75tY3L'
    })
  },
  methods: {
    upload({ file }) {
      this.cos.putObject({
        Bucket: 'hr-83-1306397861', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + parseInt(Math.random() * 1000) + file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: function(progressData) {
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        if (err) return this.$message.error(err)
        const result = this.fileList.find(item => item.uid === file.uid)
        result.status = 'success'
        result.url = 'http://' + data.Location
      })
    },
    // 预览触发的方法
    handlePictureCardPreview(file) {
      this.showDialog = true
      this.dialogImageUrl = file.url
    },
    closeFn() {
      this.showDialog = false
    },
    handleRemove(file, fileList) {
      // file可以拿到删除的文件
      // fileList 可以拿到fileList剩余的数据
      console.log(file, fileList)
      this.fileList = fileList
    },
    handleChange(file, fileList) {
      // file 可以拿到上传的文件
      // fileList 可以拿到上传后的fileList
      console.log(file, fileList)
      this.fileList = fileList
    },
    beforeUpload(file) {
      console.log(file)
      const accepts = ['image/png', 'image/jpeg']
      if (!accepts.includes(file.type)) {
        this.$message.error('请上传正确格式的图片')
        return false
      }
      if (file.size >= 1024 * 1024 * 1) {
        this.$message.error('上传图片不要超过1M')
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.hidden {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
